package com.baihuabooks.scoresys.servlets;

import com.baihuabooks.scoresys.common.DBUtil;
import com.baihuabooks.scoresys.common.Locale;
import com.baihuabooks.scoresys.entity.Response;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;

/**
 * Created by Thinkpad on 2016/5/15 0015.
 */
public class ScoreServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String customerId = req.getParameter("customerId");
        String score = req.getParameter("scores");

        Response response = new Response();
        if (StringUtils.isBlank(customerId)) {
            response.setCode(1);
            response.setDesc(Locale.get("score_error_msg_001"));
        } else if (StringUtils.isBlank(score)) {
            response.setCode(1);
            response.setDesc(Locale.get("score_error_msg_002"));
        } else {
            int custId = Integer.valueOf(customerId);
            int _score = Integer.valueOf(score);

            Connection conn = null;
            PreparedStatement stmt = null;
            PreparedStatement stmt2 = null;

            String sql = "INSERT INTO SCORE_LOG(CUST_ID, SCORE, TIME) VALUES(?,?,NOW())";
            String sqlUpdate = "UPDATE CUSTOMER SET SCORE=(SCORE+?),UPDATE_TIME=NOW() WHERE ID=?";
            try {
                conn = DBUtil.getInstance().getConnection();
                conn.setAutoCommit(false);
                stmt = conn.prepareStatement(sql);
                stmt.setInt(1, custId);
                stmt.setInt(2, _score);
                stmt.executeUpdate();

                stmt2 = conn.prepareStatement(sqlUpdate);
                stmt2.setInt(1, _score);
                stmt2.setInt(2, custId);
                stmt2.executeUpdate();

                conn.commit();

                response.setCode(0);
            } catch (SQLException e) {
                e.printStackTrace();
                response.setCode(1);
                response.setDesc("数据入库异常，请联系管理员");
            } finally {
                try {
                    conn.setAutoCommit(true);
                } catch (SQLException e) {
                }
                DBUtil.close(stmt);
                DBUtil.close(stmt2, conn);
            }

        }





        resp.getWriter().print(response.toString());
    }
}
